// index.js

const QQMapWX = require('../../utils/qqmap-wx-jssdk');
const qqmapsdk = new QQMapWX({
  key: '' // 必填
});
Page({
  data: {
    fromAddress: {},
    toAddress: {},
    distance: {},
  },

  // 获取位置
  getlocation(e) {
    let { id } = e.currentTarget.dataset;
    console.log(id)
    let that = this;
    wx.getLocation({
      type: 'wgs84', //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success(res) {
        const { latitude, longitude } = res
        console.log(res)
        wx.chooseLocation({
          latitude,
          longitude,
          success(r) {
            console.log(r)
            if (id == 1) {
              that.setData({ fromAddress: r })
            } else {
              that.setData({ toAddress: r })
            }
          }
        })
      }
    })
  },

  // 计算距离
  calculateDistance() {
    let { fromAddress, toAddress } = this.data;
    let lat1 = fromAddress.latitude;
    let lng1 = fromAddress.longitude;
    let lat2 = toAddress.latitude;
    let lng2 = toAddress.longitude;

    var _this = this;
    //调用距离计算接口
    qqmapsdk.calculateDistance({
      //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      from: {
        latitude: lat1,
        longitude: lng1
      }, //若起点有数据则采用起点坐标，若为空默认当前地址
      to: [{
        latitude: lat2,
        longitude: lng2
      }], //终点坐标
      sig: '',//签名校验
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        let hw = res.elements[0].distance //拿到距离(米)
        var dis = [];
        for (var i = 0; i < res.elements.length; i++) {
          dis.push(hw); //将返回数据存入dis数组，
        }
        _this.setData({ //设置并更新distance数据
          distance: dis
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },

  onLoad() {

  },

})
